import { IUserInfo } from '../stores/type'

const TOKEN = 'token'

const USER_INFO = 'USER_INFO'

class Localcache {
  private static saveCache(key: string, value: any = '') {
    if (value) {
      try {
        const result = JSON.stringify(value)
        uni.setStorage({
          key: key,
          data: result
        })
      } catch (error) {
        console.log('保存失败,key=', key)
      }
    }
  }

  private static getCache(key: string): any {
    const result: any = uni.getStorageSync(key)
    if (result) {
      try {
        return JSON.parse(result)
      } catch (error) {
        console.log('获取失败,key=', key)
        return ''
      }
    } else {
      return ''
    }
  }

  private static deleteCache(key: string) {
    uni.removeStorageSync(key)
  }

  /**
   * 1:清空所有缓存，慎用!!!!
   */
  public static clearCache() {
    uni.clearStorage()
  }

  /**
   * 2:保存用户token
   * @param token
   */
  public static saveToken(token: string) {
    this.saveCache(TOKEN, token)
  }

  public static getToken(): string {
    return this.getCache(TOKEN)
  }
  public static delteToken() {
    this.deleteCache(TOKEN)
  }

  public static saveUserInfo(userInfo: any) {
    this.saveCache(USER_INFO, userInfo)
  }

  public static getUserInfo(): IUserInfo {
    return this.getCache(USER_INFO)
  }
  public static delteUserInfo() {
    this.deleteCache(USER_INFO)
  }
}

export default Localcache
